import math
from datetime import datetime

from zc_core.model.items import OrderItem
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.common import parse_timestamp
from zc_core.util.deadline_filter import DeadlineFilter
from zc_core.util.encrypt_util import md5, build_sha1_order_id

# 订单采集截止天数
deadline_filter = DeadlineFilter(days=180)


# 页数
def parse_total_page(json_data):
    if json_data:
        rs_data = json_data.get('result', {}).get('orderItemDealRecordDtoPaging', {})
        total = rs_data.get('total', 0)
        empty = rs_data.get('empty', True)
        if not empty and total > 0:
            return math.ceil(total / 10)

    return 0


# 解析order列表
def parse_order_item(json_data, sku_id):
    no_more_page = False
    orders = list()
    if json_data:
        prev_order = None
        same_order_no = 1
        rows = json_data.get('result', {}).get('orderItemDealRecordDtoPaging', {}).get('data', [])
        for idx, row in enumerate(rows):
            order = OrderItem()
            order['skuId'] = sku_id
            # 采购时间  1574840734000
            order_timestamp = row.get('dealDate')
            order_time = parse_timestamp(order_timestamp)
            # 采集截止
            if deadline_filter.filter(order_time):
                order['count'] = row.get('dealCount')
                order['amount'] = row.get('dealTotalPrice') / 100
                order['orderDept'] = row.get('purchaseOrgName')
                order['deptId'] = md5(row.get('purchaseOrgName'))
                # order['supplierId'] = supplier_id
                # order['supplierName'] = supplier_name
                order['orderTime'] = order_time
                order['batchNo'] = time_to_batch_no(order_time)
                order['genTime'] = datetime.utcnow()

                if prev_order and prev_order.equals(order):
                    same_order_no = same_order_no + 1
                else:
                    same_order_no = 1
                addition = {
                    'sameOrderNo': same_order_no,
                    'orderTimeStr': order_timestamp,
                }
                sha1_id = build_sha1_order_id(order, addition)
                order['id'] = sha1_id
                order['orderId'] = sha1_id
                orders.append(order)
                prev_order = order
            else:
                no_more_page = True

    return orders, no_more_page
